package com.sfc.spiderweb.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sfc.spiderweb.util.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class MetaHandler implements MetaObjectHandler {

    /**
     * 新增数据执行
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        UserContextHolder holder = UserContextHolder.getInstance();
        setFild("createTime", new Date(), metaObject);
        setFild("createBy", holder.getUsername(), metaObject);
        setFild("updateTime", new Date(), metaObject);
        setFild("updateBy", holder.getUsername(), metaObject);
        setFild("status", 1, metaObject);
    }

    /**
     * 更新数据执行
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        UserContextHolder holder = UserContextHolder.getInstance();
        setFild("updateTime", new Date(), metaObject);
        setFild("updateBy", holder.getUsername(), metaObject);
    }

    public void setFild(String fildName, Object value, MetaObject metaObject) {
        try {
            this.setFieldValByName(fildName, value, metaObject);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}